package com.xiaoluo.a13_textswitcher;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.TextSwitcher;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * @ Created on: 2020/8/28
 * @Author: LEGION XiaoLuo
 * @ Description:
 */
public class AutoRollTextView extends TextSwitcher {

    private int mSizeCount;
    private int mIntervalTime = 3000;
    private Handler mHandler = new Handler();
    private int mAnimationIn = R.anim.anim_in_default;
    private int mAnimationOut = R.anim.anim_out_default;
    private OnAdChangeListener mChangeListener;
    private Context mContext;
    private int mCurrentIndex = 0;
    private TextView mDefaultTextView;
    private List<String> mTexts = new ArrayList<>();

    public AutoRollTextView(Context context) {
        this(context, null);
    }

    public AutoRollTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
    }

    public AutoRollTextView setAnimationIn(int animationIn) {
        mAnimationIn = animationIn;
        return this;
    }


    public AutoRollTextView setIntervalTime(int intervalTime) {
        mIntervalTime = intervalTime;
        return this;
    }

    public AutoRollTextView setAnimationOut(int animationOut) {
        mAnimationOut = animationOut;
        return this;
    }

    public void init(final List<String> texts, OnAdChangeListener listener) {
        if (texts == null || texts.size() == 0) {
            return;
        }
        mSizeCount = texts.size();
        mTexts.clear();
        mTexts.addAll(texts);
        mChangeListener = listener;
        if (mAnimationIn != -1) {
            setInAnimation(AnimationUtils.loadAnimation(mContext, mAnimationIn));
        }
        if (mAnimationOut != -1) {
            setOutAnimation(AnimationUtils.loadAnimation(mContext, mAnimationOut));
        }
        setFactory(new ViewFactory() {
            @Override
            public View makeView() {
                mDefaultTextView = new TextView(mContext);
                mDefaultTextView.setTextSize(14);
                return mDefaultTextView;

            }
        });
        setText(mTexts.get(mCurrentIndex));
        mChangeListener.diyTextView((TextView) getCurrentView(), mCurrentIndex);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mCurrentIndex++;
                if (mCurrentIndex >= mSizeCount) {
                    mCurrentIndex = 0;
                }
                setText(mTexts.get(mCurrentIndex));
                mChangeListener.diyTextView((TextView) getCurrentView(), mCurrentIndex);
                mHandler.postDelayed(this, mIntervalTime);
            }
        }, mIntervalTime);
    }

}



